<template>
	<view class="publish-container">
		<!-- 模板选择 -->
		<view class="template-section" v-if="templates.length > 0">
			<view class="section-header">
				<text class="title">选择我的活动模板</text>
				<text class="sub-title">点击标签快速创建活动</text>
			</view>
			<view class="template-tags">
				<view class="template-tag" v-for="template in templates" :key="template.id"
					:class="{ active: selectedTemplateId === template.id }" @tap="useTemplate(template)">
					<text class="tag-text">{{ template.title }}</text>
					<text class="tag-icon">✔</text>
				</view>
			</view>
		</view>

		<!-- 封面图上传 -->
		<view class="cover-upload" @tap="uploadCover">
			<view class="upload-content" v-if="!formData.coverImage">
				<view class="upload-text-wrapper">
					<image class="camera-icon-top" style="width: 100%;height: 100%;margin: 0;"
						src="/static/icons/camera.jpg" mode="aspectFit"></image>
					<!-- <text class="upload-text">可选择封面图</text> -->
				</view>
			</view>
			<view class="upload-mask" v-else>
				<image class="camera-icon-top" :src="formData.coverImage" style="width: 100%;height: 100%;margin: 0;"
					mode="aspectFit"></image>
			</view>
		</view>

		<!-- 表单区域 -->
		<view class="form-section">
			<!-- 活动标题 -->
			<view class="form-item">
				<view class="form-label">
					<view class="icon-text-wrapper">
						<image class="icon" src="/static/icons/title.png" />
						<text>活动标题</text>
					</view>
				</view>
				<input type="text" v-model="formData.title" placeholder="请输入活动标题" class="title-input" maxlength="50" />
			</view>

			<!-- 选择球队 -->
			<view class="form-item" @tap="openTeamSelector">
				<view class="form-label with-arrow">
					<view class="icon-text-wrapper">
						<image class="icon" src="/static/icons/team.png" />
						<text>选择球队</text>
					</view>
					<text class="selected-team" v-if="formData.team">{{ formData.team.name }}</text>
					<text class="arrow">></text>
				</view>
			</view>

			<!-- 活动时间 -->
			<view class="form-item" @tap="openDateTimeSelector">
				<view class="form-label with-arrow">
					<view class="icon-text-wrapper">
						<image class="icon" src="/static/icons/calendar.png" />
						<text>活动时间</text>
					</view>
					<text class="selected-time" v-if="formData.datetime">
						{{ formData.datetime.label }} {{ formData.datetime.time }}
					</text>
					<text class="arrow">></text>
				</view>
			</view>

			<!-- 编辑地理位置 -->
			<view class="form-item" @tap="openLocationSelector">
				<view class="form-label with-arrow">
					<view class="icon-text-wrapper">
						<image class="icon" src="/static/icons/location.png" />
						<text>活动地点</text>
					</view>
					<text class="selected-location" v-if="formData.location">{{ formData.location.name }}</text>
					<text class="arrow">></text>
				</view>
			</view>

			<!-- 活动种类 -->
			<view class="form-item" @tap="openSportTypeSelector">
				<view class="form-label with-arrow">
					<view class="icon-text-wrapper">
						<image class="icon" src="/static/icons/category.png" />
						<text>活动种类</text>
					</view>
					<text class="selected-type" v-if="formData.sportType">{{ formData.sportType.dictLabel }}</text>
					<text class="arrow">></text>
				</view>
			</view>

			<!-- 活动公告 -->
			<view class="form-item notice-item">
				<view class="form-label">
					<view class="icon-text-wrapper">
						<image class="icon" src="/static/icons/notice.png" />
						<text>活动公告</text>
					</view>
					<!-- <text class="history" @tap="showHistoryNotices">历史公告</text> -->
				</view>
				<view class="notice-input">
					<textarea v-model="formData.notice" placeholder="请输入活动公告" :maxlength="200" auto-height />
				</view>
			</view>

			<!-- 人数 -->
			<view class="form-item">
				<view class="form-label">
					<view class="icon-text-wrapper">
						<image class="icon" src="/static/icons/people.png" />
						<text>人数上限</text>
					</view>
				</view>
				<view class="input-wrapper">
					<input type="number" v-model="formData.maxPeople" placeholder="请输入人数限制" class="people-input"
						@input="handleMaxPeopleInput" @blur="validateMaxPeople" />
				</view>
			</view>

			<!-- 分队 -->
			<view class="form-item" v-if="formData.division.enabled !== null" @tap="goToDivision">
				<view class="form-label with-arrow">
					<view class="icon-text-wrapper">
						<image class="icon" src="/static/icons/team.png" />
						<text>分队设置</text>
					</view>
					<text class="selected-division" v-if="formData.division.enabled">
						{{ formData.division.isRandomTeam ? '随机分队' : '手动分队' }}
					</text>
					<text class="arrow">></text>
				</view>
			</view>

			<!-- 添加分队按钮 -->
			<view class="add-division" v-else @tap="addDivision">
				<text class="add-text">+ 添加分队</text>
			</view>

			<!-- 收费方式 -->
			<view class="form-item" @tap="openFeeSelector">
				<view class="form-label with-arrow">
					<view class="icon-text-wrapper">
						<image class="icon" src="/static/icons/money.png" />
						<text>收费方式</text>
					</view>
					<text class="selected-fee" v-if="formData.feeType">{{ formData.feeTypeLabel }}</text>
					<text class="arrow">></text>
				</view>
			</view>

			<!-- 开关选项 -->
			<view class="switch-items">
				<view class="switch-item">
					<view class="text-wrapper">
						<text>是否允许待定</text>
					</view>
					<switch :checked="!!formData.allowPending"
						@change="e => formData.allowPending = e.detail.value ? 1 : 0" />
				</view>
				<view class="switch-item">
					<view class="text-wrapper">
						<text>是否需要购买安全服务</text>
					</view>
					<switch :checked="!!formData.needSecurity"
						@change="e => formData.needSecurity = e.detail.value ? 1 : 0" />
				</view>
				<view class="switch-item">
					<view class="text-wrapper">
						<text>报名需填写联系方式</text>
					</view>
					<switch :checked="!!formData.needContact"
						@change="e => formData.needContact = e.detail.value ? 1 : 0" />
				</view>
				<view class="switch-item">
					<view class="text-wrapper">
						<text>私密活动</text>
					</view>
					<switch :checked="!!formData.isPrivate"
						@change="e => formData.isPrivate = e.detail.value ? 1 : 0" />
				</view>
			</view>

			<!-- 活动标签 -->
			<view class="tags-section">
				<view class="tags-header">
					<text class="title">活动标签</text>
					<text class="sub-title">最多选择3个标签</text>
				</view>
				<view class="tags-list">
					<text class="tag" v-for="tag in availableTags" :key="tag"
						:class="{ selected: selectedTags.includes(tag) }" @tap="toggleTag(tag)">{{ tag }}</text>
					<text class="tag add-tag" @tap="showCustomTag" v-if="selectedTags.length < 3">+</text>
				</view>
			</view>
		</view>

		<!-- 底部操作区 -->
		<view class="bottom-actions">
			<view class="save-template">
				<checkbox-group @change="onSaveTemplateChange">
					<label class="checkbox-label" :class="{ disabled: templates.length >= 5 }">
						<checkbox :checked="saveAsTemp" :disabled="templates.length >= 5"
							style="transform: scale(0.8);" />
						<text class="checkbox-text">保存为模板</text>
						<text v-if="templates.length >= 5" class="template-limit-tip">最多创建5个模板</text>
					</label>
				</checkbox-group>
			</view>
			<button class="publish-btn" @tap="handlePublish">发布活动</button>
		</view>

		<!-- 添加球队选择器组件 -->
		<team-selector :show.sync="showTeamSelector" :teams="myTeams" :value="formData.team" @select="onTeamSelected" />

		<!-- 添加时间选择器组件 -->
		<date-time-selector :show.sync="showDateTimeSelector" @select="onDateTimeSelected" />

		<!-- 添加位置选择器组件 -->
		<location-selector ref="locationSelector" @select="onLocationSelected" />

		<!-- 添加运动类型选择器组件 -->
		<sport-type-selector :show.sync="showSportTypeSelector" v-model="formData.sportType"
			@select="onSportTypeSelected" />

		<!-- 添加收费方式选择器组件 -->
		<fee-type-selector :show.sync="showFeeSelector" v-model="formData.feeType" @select="onFeeTypeSelected" />

		<!-- 修改自定义标签组件引用 -->
		<tag-popup :show.sync="showCustomTagInput" @confirm="addCustomTag" />
	</view>
</template>

<script>
	import TeamSelector from '@/components/TeamSelector.vue'
	import DateTimeSelector from '@/components/DateTimeSelector.vue'
	import LocationSelector from '@/components/LocationSelector.vue'
	import SportTypeSelector from '@/components/SportTypeSelector.vue'
	import FeeTypeSelector from '@/components/FeeTypeSelector.vue'
	import TagPopup from '@/components/tag-popup/index.vue'
	import {
		uploadCover,
		addActivity,
		getMyTemplates
	} from '@/api/youqiu/activity.js'

	import {
		saveAsTemplate
	} from '@/api/youqiu/template.js'
	import {
		myCreateTeam
	} from '@/api/youqiu/team.js'
	import {
		mapGetters
	} from 'vuex'

	export default {
		name: 'PublishPage',
		components: {
			TeamSelector,
			DateTimeSelector,
			LocationSelector,
			SportTypeSelector,
			FeeTypeSelector,
			TagPopup
		},
		data() {
			return {
				showSportTypeSelector: false,
				showFeeSelector: false,
				formData: {
					// 基本信息
					title: '', // 活动标题
					ossId: '', // 封面图OSS ID
					coverImage: '', // 封面图URL
					teamId: '', // 球队ID
					activityTime: '', // 活动时间
					location: '', // 活动地点
					latitude: '', // 纬度
					longitude: '', // 经度
					sportType: '', // 运动类型
					notice: '', // 活动公告
					maxPeople: '', // 人数上限
					feeType: 'free', // 收费类型ID
					feeTypeLabel: '', // 收费类型名称

					// 活动设置
					needSecurity: 0, // 是否需要安全服务 (0否1是)
					needContact: 1, // 是否需要联系方式 (0否1是)
					allowPending: 0, // 是否允许待定 (0否1是)
					isPrivate: 0, // 是否私密活动 (0否1是)
					tags: [], // 活动标签数组

					// 分队信息
					division: {
						enabled: null, // 初始值为null，表示未添加分队
						canChooseTeam: false,
						teamLimit: '',
						isRandomTeam: false,
						teams: []
					},

					// 选择的球队信息
					team: {
						id: '',
						name: '',
						logo: '',
						memberCount: 0,
						activityCount: 0
					}
				},
				myTeams: [],
				tagsList: [{
						id: 1,
						name: '野生局'
					},
					{
						id: 2,
						name: '散客场'
					},
					{
						id: 3,
						name: '女足'
					},
					{
						id: 4,
						name: '真草'
					},
					{
						id: 5,
						name: '竞技性强'
					}
				],
				showCustomTagInput: false,
				customTagValue: '',
				showTeamSelector: false,
				showDateTimeSelector: false,
				templates: [], // 模板列表
				saveAsTemp: false, // 是否保存为模板
				// 可选标签列表
				availableTags: [
					'野生局',
					'散客场',
					'女足',
					'真草',
					'竞技性强'
				],
				// 已选标签
				selectedTags: [],
				selectedTemplateId: '', // 当前选中的模板ID
			}
		},
		watch: {
			// 监听模板数量变化
			'templates.length': {
				immediate: true,
				handler(newVal) {
					// 如果模板数量达到上限，取消勾选并禁用
					if (newVal >= 5) {
						this.saveAsTemp = false
					}
				}
			}
		},
		onShow() {
			// 每次页面显示时重新获取球队信息
			const publishTeamInfo = uni.getStorageSync('publish_team_info')
			if (publishTeamInfo) {
				this.formData.team = publishTeamInfo
				this.myCreateTeam() // 重新获取完整的球队信息
			}
			this.getTemplates()
		},
		onLoad(options) {
			this.myCreateTeam()
			this.getTemplates()
		},
		onUnload() {
			// 页面卸载时清空数据
			this.formData = {
				title: '',
				ossId: 0,
				coverImage: '',
				team: null,
				time: '',
				location: null,
				category: '',
				notice: '',
				maxPeople: '',
				division: null,
				fee: '自定义收费',
				needSecurity: false,
				needContact: false,
				allowPending: false,
				isPrivate: false,
				tags: [],
				datetime: null,
				sportType: null,
				feeType: '',
				feeTypeLabel: ''
			}
			// 清除本地存储
			uni.removeStorageSync('publish_team_info')
		},
		computed: {},
		methods: {
			// 修改获取球队列表方法
			myCreateTeam() {
				myCreateTeam().then(res => {
					console.log('myCreateTeam', res)
					this.myTeams = res.data
					// 如果有传入的球队ID，找到对应的整球队信息
					if (this.formData.team && this.formData.team.id) {
						const selectedTeam = this.myTeams.find(team => team.id === this.formData.team.id)
						if (selectedTeam) {
							this.formData.team = selectedTeam
						}
					}
				})
			},
			// 上传封面图
			uploadCover() {
				uni.chooseImage({
					count: 1, // 最多选择的图片张数
					sizeType: ['compressed'], // 可以指定是原图还是压缩图，默认二者都有
					sourceType: ['album', 'camera'], // 从相册选择或使用相机
					success: (res) => {
						console.log('选择图片成功：', res)
						// 获取临时文件路径
						const tempFilePath = res.tempFilePaths[0]

						// 更新表单数据
						this.formData.coverImage = tempFilePath

						// 这里可以添加务器的逻辑
						// this.uploadToServer(tempFilePath)
						let data = {
							name: 'file',
							filePath: tempFilePath
						}

						uploadCover(data).then(response => {
							//store.commit('SET_AVATAR', baseUrl + response.imgUrl)
							console.log('uploadCover', response)
							uni.showToast({
								title: "上传成功",
								icon: 'success'
							})
							this.formData.coverImage = response.data.url
							this.formData.ossId = response.data.ossId
							uni.navigateBack()
						})
					},
					fail: (err) => {
						console.error('选择图片失败：', err)
						uni.showToast({
							title: '选择图片失败',
							icon: 'none'
						})
					}
				})
			},

			// 上传图片到服务器（如果���要的话）
			uploadToServer(tempFilePath) {
				uni.uploadFile({
					url: 'your-upload-url', // 替为你的上传接口
					filePath: tempFilePath,
					name: 'file',
					success: (uploadRes) => {
						console.log('上传成功：', uploadRes)
						// 处理上传功后的逻辑
					},
					fail: (err) => {
						console.error('上传失败：', err)
						uni.showToast({
							title: '上传失败',
							icon: 'none'
						})
					}
				})
			},
			// 处理发布
			async handlePublish() {
				try {
					// 基本表单验证
					if (!this.formData.title) {
						uni.showToast({
							title: '请输入活动标题',
							icon: 'none'
						})
						return false
					}

					if (!this.formData.coverImage) {
						uni.showToast({
							title: '请上传封面图',
							icon: 'none'
						})
						return false
					}

					if (!this.formData.team) {
						uni.showToast({
							title: '请选择球队',
							icon: 'none'
						})
						return false
					}

					// 验证并格式化活动时间
					const activityTime = this.formatDateTime(this.formData.datetime)
					if (!this.formData.datetime || !this.formData.datetime.time) {
						uni.showToast({
							title: '请选择活动时间',
							icon: 'none'
						})
						return false
					}

					if (!this.formData.location) {
						uni.showToast({
							title: '请选择活动地点',
							icon: 'none'
						})
						return false
					}

					if (!this.formData.sportType) {
						uni.showToast({
							title: '请选择活动种类',
							icon: 'none'
						})
						return false
					}

					// 构造提交数据
					const submitData = {
						title: this.formData.title,
						ossId: this.formData.ossId,
							coverImage: this.formData.coverImage,
							teamId: this.formData.team?.id || '',
							activityTime: activityTime,
							location: this.formData.location.name,
							latitude: this.formData.location.latitude,
							longitude: this.formData.location.longitude,
							sportType: this.formData.sportType.dictValue,
							notice: this.formData.notice,
							maxPeople: this.formData.maxPeople,
							feeType: this.formData.feeType,
							feeTypeLabel: this.formData.feeTypeLabel,
							needSecurity: Number(this.formData.needSecurity),
							needContact: Number(this.formData.needContact),
							allowPending: Number(this.formData.allowPending),
							isPrivate: Number(this.formData.isPrivate),
							tags: this.selectedTags.join(','),
							division: {
								enabled: this.formData.division.enabled ? 1 : 0,
								canChooseTeam: this.formData.division.canChooseTeam ? 1 : 0,
								teamLimit: this.formData.division.teamLimit,
								isRandomTeam: this.formData.division.isRandomTeam ? 1 : 0,
								teams: this.formData.division.teams
							}
					}

					// 发布活动
					const response = await addActivity(submitData)

					if (response.code === 200) {
						// 如果选择保存为模板
						if (this.saveAsTemp) {
							console.log('saveAsTemp', this.formData)
							try {
								// 构造完整的模板内容
								const templateData = {
									title: this.formData.title,
									coverImage: this.formData.coverImage || '',
									team: {
										id: this.formData.team ? this.formData.team.id : null,
										name: this.formData.team ? this.formData.team.name : '',
										logo: this.formData.team ? this.formData.team.logo : '',
										memberCount: this.formData.team ? this.formData.team
											.memberCount : 0,
										activityCount: this.formData.team ? this.formData.team
											.activityCount : 0
									},
									datetime: {
										label: this.formData.datetime ? this.formData.datetime.label : '',
										time: this.formData.datetime ? this.formData.datetime.time : ''
									},
									location: {
										name: this.formData.location ? this.formData.location.name : '',
										address: this.formData.location ? this.formData.location.address : '',
										latitude: this.formData.location ? this.formData.location
											.latitude : null,
										longitude: this.formData.location ? this.formData.location
											.longitude : null
									},
									sportType: {
										dictValue: this.formData.sportType ? this.formData.sportType.dictValue :
											'',
										dictLabel: this.formData.sportType ? this.formData.sportType.dictLabel : ''
									},
									notice: this.formData.notice || '',
									maxPeople: this.formData.maxPeople ? this.formData.maxPeople : 0,
									visibility: this.formData.isPrivate ? 0 : 1,
									feeType: this.formData.feeType || 'free',
									feeAmount: this.formData.feeAmount ? this.formData.feeAmount : 0,
									description: this.formData.description || '',
									tags: this.selectedTags.join(','),
									division: {
										enabled: this.formData.division.enabled ? 1 : 0,
										canChooseTeam: this.formData.division.canChooseTeam ? 1 : 0,
										teamLimit: this.formData.division.teamLimit,
										isRandomTeam: this.formData.division.isRandomTeam ? 1 : 0,
										teams: this.formData.division.teams.map(team => ({
											name: team.name
										}))
									},
									divisionType: this.formData.division.isRandomTeam ? 1 : 0,
									needContact: this.formData.needContact ? 1 : 0,
									needSecurity: this.formData.needContact ? 1 : 0,
									isPrivate: this.formData.isPrivate ? 1 : 0,
									allowPending: this.formData.isPrivate ? 1 : 0,
									teamCount: this.formData.division.teams.length,
									teamNames: this.formData.division.teams.map(t => t.name || ''),
									teamColors: this.formData.division.teams.map(() => '#FF6B35'),
									teamLogos: this.formData.division.teams.map(() => '')

								}

								// 保存模板
								await saveAsTemplate({
									title: this.formData.title,
									template: JSON.stringify(templateData)
								})

								uni.showToast({
									title: '模板保存成功',
									icon: 'success'
								})
							} catch (error) {
								console.error('保存模板失败:', error)
								uni.showToast({
									title: '模板保存失败',
									icon: 'none'
								})
							}
						}

						uni.showToast({
							title: '发布活动成功',
							icon: 'success'
						})

						// 延迟跳转到首页
						setTimeout(() => {
							uni.switchTab({
								url: '/pages/index/index'
							})
						}, 1500)
					}
				} catch (error) {
					console.error('发布失败:', error)
					uni.showToast({
						title: '发布失败',
						icon: 'none'
					})
				}
			},
			// 表单验证
			validateForm() {
				if (!this.formData.title) {
					uni.showToast({
						title: '请输入活动标题',
						icon: 'none'
					})
					return false
				}

				if (!this.formData.coverImage) {
					uni.showToast({
						title: '请上传封面图',
						icon: 'none'
					})
					return false
				}

				if (!this.formData.team) {
					uni.showToast({
						title: '请选择球队',
						icon: 'none'
					})
					return false
				}

				if (!this.formData.datetime) {
					uni.showToast({
						title: '请选择活动时间',
						icon: 'none'
					})
					return false
				}

				if (!this.formData.location) {
					uni.showToast({
						title: '请选择活动地点',
						icon: 'none'
					})
					return false
				}

				if (!this.formData.sportType) {
					uni.showToast({
						title: '请选择活动种类',
						icon: 'none'
					})
					return false
				}

				if (!this.formData.notice) {
					uni.showToast({
						title: '请填写活动公告',
						icon: 'none'
					})
					return false
				}

				if (!this.formData.maxPeople || parseInt(this.formData.maxPeople) <= 0) {
					uni.showToast({
						title: '请设置有效的人数上限',
						icon: 'none'
					})
					return false
				}

				if (!this.formData.feeType) {
					uni.showToast({
						title: '请选择收费方式',
						icon: 'none'
					})
					return false
				}

				return true
			},
			// 打开球队选择器
			openTeamSelector() {
				console.log('当前选中的球队:', this.formData.team)
				// 确保在打开选择器前重置状态
				this.$nextTick(() => {
					this.showTeamSelector = true
				})
			},
			// 处理球队选择
			onTeamSelected(team) {
				console.log('选中球队:', team)
				this.formData.team = team
				this.showTeamSelector = false
			},
			// 打开时间选择器
			openDateTimeSelector() {
				this.showDateTimeSelector = true
			},
			// 处理时间选择
			onDateTimeSelected(datetime) {
				this.formData.datetime = datetime
				console.log('选择的时间:', datetime) // 添加日志
			},
			// 跳转到分队设置页面
			goToDivision() {
				uni.navigateTo({
					url: '/pages/activity/division/index?division=' + JSON.stringify(this.formData.division),
					events: {
						// 监听分队数据更新
						updateDivision: (division) => {
							// 使用Vue的响应式方法更新数据
							this.$set(this.formData, 'division', division)
						}
					}
				})
			},
			// 接收分队设置结果
			onDivisionSet(settings) {
				console.log('收分队设置：', settings) // 加日志
				if (settings && settings.enabled) {
					this.formData.division = settings
				}
			},
			// 打开位置选择器
			openLocationSelector() {
				// 添加延时处理
				setTimeout(() => {
					this.$refs.locationSelector.open()
				}, 100)
			},
			// 处理位置选择
			onLocationSelected(location) {
				this.formData.location = location
			},
			// 打开运动类型选择器

			openSportTypeSelector() {
				this.showSportTypeSelector = true
			},
			// 处理运动类型选择
			onSportTypeSelected(type) {
				console.log('选中的运动类型：', type) // 添加日志查看数据
				this.formData.sportType = type
			},
			// 处理人数上限输入
			handleMaxPeopleInput(e) {
				let value = e.detail.value
				// 移除非字字符
				value = value.replace(/\D/g, '')
				// 移除前导零
				value = value.replace(/^0+/, '')

				if (value) {
					// 确保数值大于0且不超过999
					let num = parseInt(value)
					if (num > 999) {
						value = '999'
					} else if (num <= 0) {
						value = '1'
					}
				}
				this.formData.maxPeople = value
			},
			// 失去焦点时验证
			validateMaxPeople() {
				if (!this.formData.maxPeople || parseInt(this.formData.maxPeople) <= 0) {
					this.formData.maxPeople = '1'
					uni.showToast({
						title: '人数必须大于0',
						icon: 'none'
					})
				}
			},
			// 显示历史公告
			showHistoryNotices() {
				// 这里添加显示历史公告的逻辑
				uni.showToast({
					title: '暂无历史公告',
					icon: 'none'
				})
			},
			// 关闭分队设置
			closeDivision() {
				this.formData.division = null
			},
			// 打开收费方式选择器
			openFeeSelector() {
				this.showFeeSelector = true
			},
			// 处理收费方式选择
			onFeeTypeSelected(type) {
				console.log('选中的收费方式：', type)
				if (type) {
					this.formData.feeType = type.dictValue
					this.formData.feeTypeLabel = type.dictLabel
				}
			},
			// 判断标签是否被选中
			isTagSelected(tag) {
				return this.formData.tags.some(t => t.id === tag.id)
			},
			// 切换标签选中状态
			toggleTag(tag) {
				const index = this.selectedTags.indexOf(tag)
				if (index > -1) {
					// 如果已选中，则取消选中
					this.selectedTags.splice(index, 1)
				} else {
					// 如果未选中且未超过限制，则选中
					if (this.selectedTags.length < 3) {
						this.selectedTags.push(tag)
					} else {
						uni.showToast({
							title: '最多选择3个标签',
							icon: 'none'
						})
					}
				}
			},
			// 显示自定义标签输入
			showCustomTag() {
				if (this.selectedTags.length >= 3) {
					uni.showToast({
						title: '最多选择3个标签',
						icon: 'none'
					})
					return
				}
				this.showCustomTagInput = true
			},
			// 添加自定义标签
			addCustomTag(content) {
				if (content) {
					// 检查标签长度
					if (content.length > 6) {
						uni.showToast({
							title: '标签最多6个字',
							icon: 'none'
						})
						return
					}

					// 检查是否已存在相同的标签
					if (this.availableTags.includes(content)) {
						// 如果标签已存在但未选中，且未达到选择上限，则选中它
						if (!this.selectedTags.includes(content) && this.selectedTags.length < 3) {
							this.selectedTags.push(content)
						}
					} else {
						// 添加新标签到可选列表
						this.availableTags.push(content)

						// 如果未达到选择上限，自动选中新标签
						if (this.selectedTags.length < 3) {
							this.selectedTags.push(content)
						} else {
							uni.showToast({
								title: '最多选择3个标签',
								icon: 'none'
							})
						}
					}
				}
			},
			// 获取模板列表
			async getTemplates() {
				try {
					const res = await getMyTemplates()
					if (res.code === 200) {
						this.templates = res.data || []
					}
				} catch (error) {
					console.error('获取模板失败:', error)
				}
			},
			// 使用模板
			async useTemplate(template) {
				this.selectedTemplateId = template.id
				try {
					// 移除不需要的系统字段
					const {
						id,
						createTime,
						...templateData
					} = template

					// 处理日期时间
					if (templateData.activityTime) {
						const now = new Date()
						const today = new Date(now.getFullYear(), now.getMonth(), now.getDate())

						// 设置默认时间为今天的相同时间点
						const templateTime = new Date(templateData.activityTime)
						today.setHours(templateTime.getHours())
						today.setMinutes(templateTime.getMinutes())

						// 格式化日期标签
						let dateLabel
						const todayDate = new Date()
						const tomorrowDate = new Date(todayDate)
						tomorrowDate.setDate(todayDate.getDate() + 1)

						if (today.toDateString() === todayDate.toDateString()) {
							dateLabel = '今天'
						} else if (today.toDateString() === tomorrowDate.toDateString()) {
							dateLabel = '明天'
						} else {
							dateLabel =
								`${today.getFullYear()}-${String(today.getMonth() + 1).padStart(2, '0')}-${String(today.getDate()).padStart(2, '0')}`
						}

						this.formData.datetime = {
							label: dateLabel,
							time: `${String(today.getHours()).padStart(2, '0')}:${String(today.getMinutes()).padStart(2, '0')}`
						}
					}

					// 回填其他数据
					this.formData = {
						...this.formData,
						title: templateData.title,
						ossId: templateData.ossId,
						coverImage: templateData.coverImage,
						team: templateData.team,
						location: templateData.location,
						sportType: templateData.sportType,
						notice: templateData.notice,
						maxPeople: templateData.maxPeople,
						division: templateData.division || {
							enabled: null,
							canChooseTeam: false,
							teamLimit: '',
							isRandomTeam: false,
							teams: []
						},
						feeType: templateData.feeType,
						feeTypeLabel: templateData.feeTypeLabel,
						needSecurity: templateData.needSecurity || 0,
						needContact: templateData.needContact || 0,
						allowPending: templateData.allowPending || 0,
						isPrivate: templateData.isPrivate || 0
					}

					// 处理标签
					if (templateData.tags) {
						this.selectedTags = templateData.tags.split(',')
					}

					uni.showToast({
						title: '已应用模板',
						icon: 'success'
					})
				} catch (error) {
					console.error('应用模板失败:', error)
					uni.showToast({
						title: '应用模板失败',
						icon: 'none'
					})
				}
			},
			// 格式化日期时间
			formatDateTime(datetime) {
				if (!datetime || !datetime.time || !datetime.label) return ''

				// 获取当前日期
				const now = new Date()
				const today = new Date(now.getFullYear(), now.getMonth(), now.getDate())
				const tomorrow = new Date(today)
				tomorrow.setDate(tomorrow.getDate() + 1)

				// 解析时间
				const [hours, minutes] = datetime.time.split(':')
				if (!hours || !minutes || isNaN(hours) || isNaN(minutes)) return ''

				// 根据label确定具体日期
				let date
				switch (datetime.label) {
					case '今天':
						date = today
						break
					case '明天':
						date = tomorrow
						break
					default:
						// 如果是具体日期(格式如: "2024-03-21")
						date = new Date(datetime.label)
				}

				// 设置时间
				date.setHours(parseInt(hours))
				date.setMinutes(parseInt(minutes))

				// 返回标准格式 yyyy-MM-dd HH:mm:ss
				return this.formatDate(date)
			},
			// 日期格式化工具方法
			formatDate(date) {
				if (!(date instanceof Date) || isNaN(date)) return ''

				const year = date.getFullYear()
				const month = String(date.getMonth() + 1).padStart(2, '0')
				const day = String(date.getDate()).padStart(2, '0')
				const hours = String(date.getHours()).padStart(2, '0')
				const minutes = String(date.getMinutes()).padStart(2, '0')
				const seconds = '00'

				return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
			},
			// 获取收费类型标签
			getFeeTypeLabel(type) {
				const feeTypes = {
					free: '免费活动',
					fixed: '固定收费',
					deposit: '保证金',
					aa: 'AA收费',
					custom: '自定义收费'
				}
				return feeTypes[type] || '自定义收费'
			},
			// 添加分队
			addDivision() {
				// 初始化分队数据
				this.$set(this.formData, 'division', {
					enabled: true,
					isRandomTeam: false,
					canChooseTeam: false,
					teamLimit: '',
					teams: [{
							name: '红队'
						},
						{
							name: '蓝队'
						}
					]
				})
				this.goToDivision()
			},
			// 处理保存为模板复选框变化
			onSaveTemplateChange(e) {
				if (this.templates.length >= 5) {
					uni.showToast({
						title: '最多创建5个模板',
						icon: 'none'
					})
					this.saveAsTemp = false
					return
				}
				this.saveAsTemp = e.detail.value.length > 0
			},
		}
	}
</script>

<style lang="scss" scoped>
	.publish-container {
		padding: 20rpx;
		background: #f5f5f5;
		min-height: 100vh;

		.template-section {
			background: #fff;
			padding: 20rpx;
			margin-bottom: 20rpx;

			.section-header {
				margin-bottom: 16rpx;

				.title {
					font-size: 28rpx;
					font-weight: bold;
					color: #333;
				}

				.sub-title {
					font-size: 22rpx;
					color: #999;
					margin-left: 12rpx;
				}
			}

			.template-tags {
				display: flex;
				flex-wrap: wrap;
				gap: 16rpx;

				.template-tag {
					padding: 12rpx 24rpx;
					background: #f8f8f8;
					border-radius: 24rpx;
					font-size: 24rpx;
					color: #666;
					border: 1px solid #eee;
					transition: all 0.2s;
					display: flex;
					align-items: center;

					.tag-text {
						margin-right: 8rpx;
					}

					.tag-icon {
						font-size: 20rpx;
						color: #07c160;
						opacity: 0;
						transition: opacity 0.2s;
					}

					&.active {
						background: #07c160;
						color: #fff;
						border-color: #07c160;

						.tag-icon {
							color: #fff;
							opacity: 1;
						}
					}

					&:active {
						opacity: 0.8;
					}
				}
			}
		}

		.cover-upload {
			position: relative;
			height: 300rpx;
			border-radius: 20rpx;
			margin-bottom: 20rpx;
			overflow: hidden;

			.upload-content {
				position: absolute;
				top: 0;
				left: 0;
				right: 0;
				bottom: 0;
				z-index: 1;

				.camera-bg {
					position: absolute;
					top: 0;
					left: 0;
					width: 100%;
					height: 100%;
					object-fit: cover;
				}

				.upload-text-wrapper {
					position: absolute;
					top: 0;
					left: 0;
					right: 0;
					bottom: 0;
					display: flex;
					flex-direction: column;
					align-items: center;
					justify-content: center;
					z-index: 2;
				}
			}

			.cover-preview {
				width: 100%;
				height: 100%;
				object-fit: cover;
			}

			.upload-mask {
				position: absolute;
				top: 0;
				left: 0;
				right: 0;
				bottom: 0;
				background: rgba(0, 0, 0, 0.3);
				display: flex;
				flex-direction: column;
				align-items: center;
				justify-content: center;
				z-index: 2;
			}

			.camera-icon,
			.camera-icon-top {
				width: 80rpx;
				height: 80rpx;
				margin-bottom: 20rpx;
			}

			.upload-text {
				color: black;
				font-size: 28rpx;
				text-shadow: 0 1px 2px rgba(0, 0, 0, 0.3);
			}
		}

		.form-section {
			background: #fff;
			border-radius: 20rpx;
			padding: 20rpx;
			margin-bottom: 120rpx;

			.form-item {
				padding: 30rpx 20rpx;
				border-bottom: 1rpx solid #eee;
				display: flex;
				align-items: center;

				.form-label {
					width: auto;
					min-width: 220rpx;
					display: flex;
					align-items: center;
					position: relative;

					.icon-text-wrapper {
						display: flex;
						align-items: center;
						width: 220rpx;
						flex-shrink: 0;
					}

					.icon {
						width: 40rpx;
						height: 40rpx;
						margin-right: 20rpx;
						flex-shrink: 0;
					}

					>text:first-of-type {
						font-size: 28rpx;
					}

					.sub-text,
					.selected-team,
					.selected-time,
					.selected-location,
					.selected-type,
					.selected-fee {
						flex: 1;
						text-align: right;
						padding-right: 40rpx;
						color: #666;
						font-size: 28rpx;
					}

					.arrow {
						position: absolute;
						right: 0;
						color: #999;
						font-size: 28rpx;
						padding-right: 20rpx;
					}

					.division-status {
						flex: 1;
						display: flex;
						justify-content: flex-end;
						align-items: center;
						padding-right: 40rpx;

						.status-text {
							color: #666;
							font-size: 28rpx;
						}

						.close-icon {
							margin-left: 10rpx;
							color: #999;
							font-size: 32rpx;
							padding: 0 10rpx;
						}
					}

					&.with-arrow {
						width: 100%;

						.selected-team,
						.selected-time,
						.selected-location,
						.selected-type,
						.selected-fee {
							flex: 1;
							text-align: right;
							padding-right: 40rpx;
							color: #666;
							font-size: 28rpx;
						}

						.arrow {
							position: absolute;
							right: 0;
							color: #999;
							font-size: 28rpx;
							padding-right: 20rpx;
						}
					}
				}

				textarea,
				input {
					flex: 1;
					margin-left: 20rpx;
					font-size: 28rpx;
				}

				&.notice-item {
					flex-direction: column;
					align-items: flex-start;

					.form-label {
						margin-bottom: 20rpx;

						.history {
							color: #666;
							font-size: 28rpx;
						}
					}

					.notice-input {
						width: 100%;

						textarea {
							width: 100%;
							min-height: 120rpx;
							font-size: 28rpx;
							line-height: 1.5;
						}
					}
				}

				.input-wrapper {
					flex: 1;
					display: flex;
					padding-right: 20rpx;

					.title-input {
						flex: 1;
						height: 80rpx;
						font-size: 28rpx;
						padding: 0 20rpx;
					}
				}

				.people-input {
					width: 200rpx;
					text-align: right;
					font-size: 28rpx;
					color: #333;
				}
			}
		}

		.switch-items {
			.switch-item {
				padding: 30rpx 20rpx;
				display: flex;
				align-items: center;
				border-bottom: 1rpx solid #eee;
				position: relative;

				// 左侧文字容器
				.text-wrapper {
					width: auto;
					flex-shrink: 0;
					white-space: nowrap;
					margin-right: 20rpx;
					margin-bottom: 30rpx;
				}

				>text:first-of-type {
					font-size: 28rpx;
				}

				switch {
					margin-left: auto;
					transform: scale(0.8);
					margin-bottom: 30rpx;
				}

				.tips {
					position: absolute;
					left: 20rpx;
					bottom: 20rpx;
					font-size: 24rpx;
					color: #999;
				}

				&:first-child {
					padding-bottom: 50rpx;
				}
			}

			.switch-item:last-child {
				border-bottom: none;
			}
		}

		.tags-section {
			padding: 20rpx 30rpx;
			background: #fff;
			margin-top: 20rpx;

			.tags-header {
				display: flex;
				align-items: center;
				margin-bottom: 20rpx;

				.title {
					font-size: 32rpx;
					color: #333;
					font-weight: bold;
				}

				.sub-title {
					font-size: 24rpx;
					color: #999;
					margin-left: 20rpx;
				}
			}

			.tags-list {
				display: flex;
				flex-wrap: wrap;
				gap: 20rpx;

				.tag {
					padding: 10rpx 30rpx;
					background: #f5f5f5;
					border-radius: 30rpx;
					font-size: 28rpx;
					color: #333;

					&.selected {
						background: #ff6b35;
						color: #fff;
					}

					&.add-tag {
						background: #fff;
						border: 1px solid #eee;
						padding: 10rpx 20rpx;
						min-width: 44rpx;
						text-align: center;

						&:active {
							background: #f5f5f5;
						}
					}
				}
			}
		}

		.bottom-actions {
			position: fixed;
			bottom: 0;
			left: 0;
			right: 0;
			padding: 16rpx 30rpx;
			background: #fff;
			box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05);
			display: flex;
			align-items: center;
			justify-content: space-between;

			.save-template {
				flex: 1;

				.checkbox-label {
					display: flex;
					align-items: center;
					font-size: 26rpx;
					color: #666;

					&.disabled {
						opacity: 0.5;
						pointer-events: none;
					}

					.checkbox-text {
						margin-left: 12rpx;
						margin-right: 8rpx;
					}

					.template-limit-tip {
						margin-left: 12rpx;
						font-size: 22rpx;
						color: #ff6b35;
					}
				}
			}

			.publish-btn {
				width: 180rpx;
				height: 64rpx;
				line-height: 64rpx;
				background: #07c160;
				color: #fff;
				border-radius: 32rpx;
				font-size: 28rpx;
				border: none;
				margin-left: 20rpx;
				padding: 0;

				&:active {
					opacity: 0.9;
				}

				&::after {
					border: none;
				}
			}
		}

		.add-division {
			background: #fff;
			padding: 30rpx;
			margin-top: 20rpx;
			display: flex;
			align-items: center;
			justify-content: center;

			.add-text {
				color: #666;
				font-size: 28rpx;

				&:active {
					opacity: 0.7;
				}
			}
		}
	}
</style>